package com.yonyou.lxp.xutils3test.ui.bitmap;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.yonyou.lxp.xutils3test.R;
import com.yonyou.lxp.xutils3test.adapter.MyImageAdapter;
import com.yonyou.lxp.xutils3test.network.Http;
import com.yonyou.lxp.xutils3test.ui.BaseFragment;

import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ContentView(R.layout.fragment_bitmap)
public class BitmapFragment extends BaseFragment {

    @ViewInject(R.id.lv_img)
    private ListView lv_img;

    private Http http = new Http();
    private List list = new ArrayList();
    private MyImageAdapter adapter;

    public BitmapFragment() {
    }

    public static BitmapFragment newInstance(String param1, String param2) {
        BitmapFragment fragment = new BitmapFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        adapter=new MyImageAdapter(mContext,list);
        lv_img.setAdapter(adapter);
        list.clear();
        adapter.notifyDataSetChanged();
        http.send("http://www.youzi4.com/", new Http.MyCallBack() {
            @Override
            public void callback(String result) {
                list.addAll(getImgSrcList(result));
                adapter.notifyDataSetChanged();
            }
        }, mContext, true);
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    /**
     * 得到网页中图片的地址
     */
    public static List<String> getImgSrcList(String htmlStr) {
        List<String> pics = new ArrayList<String>();

        String regEx_img = "<img.*?src=\"http://(.*?).jpg\""; // 图片链接地址
        Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        Matcher m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            String src = m_image.group(1);
            if (src.length() < 100) {
                pics.add("http://" + src + ".jpg");
            }
        }
        return pics;
    }


}
